package produce_consume;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class TaskQueue2<T> {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    private Queue<T> queue;
    private static final int DEFAULT_CAPACITY = 10;
    private final int MAX_CAPACITY;

    public TaskQueue2() {
        this(DEFAULT_CAPACITY);
    }

    public TaskQueue2(int capacity) {
        this.MAX_CAPACITY = capacity;
        this.queue = new LinkedList<>();
    }

    public void offer(T e) throws InterruptedException {
        lock.lock();
        try {
            while (queue.size() >= MAX_CAPACITY) {
                condition.await();
            }
            queue.add(e);
            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }

    public T poll() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                condition.await();
            }
            condition.signalAll();
            return queue.poll();
        }finally {
            lock.unlock();
        }

    }
}